package com.diyunapp.xilinapp.me;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;

public class VersionsUpdateActivity extends StatusBarFragmentActivity implements View.OnClickListener {

    @Bind(R.id.go_back1)
    ImageView goBack1;
    @Bind(R.id.versions_num)
    TextView versionsNum;
    @Bind(R.id.sure_to_recharge)
    TextView sureToRecharge;
    @Bind(R.id.versions_update0)
    TextView verdionsUpdate0;
    private Dialog prompt_Dialog;
    private TextView prompt_title_tv;
    private TextView prompt_info_tv;
    private TextView prompt_button_tv;

    //版本检测需要更新时的提示框
    private Dialog set_Dialog;
    private TextView setDialog_title_tv;
    private TextView setDialog_promptinfo_tv;
    private EditText setDialog_editinfo_et;
    private TextView setDialog_cancel_bt;
    private TextView setDialog_confirm_bt;
    private boolean download_over = false;

    private ApkInfo myApkinfo;
    private boolean update_flag = false;
    //自定义下载后的apk存放路径
    private File myfile;

    //APP下载进程提示框
    private ProgressDialog dialog;
    private HttpHandler handler;

    public String url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_versions_update);
        ButterKnife.bind(this);
        View headView;
        headView = findViewById(R.id.verup_menubar_inc);
        super.MenuWidget(headView);
        check_update1();
        initView();
        sureToRecharge.setOnClickListener(this);
        goBack1.setOnClickListener(this);
//        updateApk();
    }

    private void initView() {
        //各类操作提示对话框相关功能处理
        View promptView = LayoutInflater.from(this).inflate(R.layout.dialog_prompt, null);
        prompt_title_tv = (TextView)promptView.findViewById(R.id.prompt_dialog_title);
        prompt_info_tv = (TextView)promptView.findViewById(R.id.prompt_dialog_info);
        prompt_button_tv = (TextView)promptView.findViewById(R.id.prompt_dialog_button);
        prompt_button_tv.setOnClickListener(this);
        prompt_Dialog = new Dialog(this, R.style.selfdefine_dailog_style);
        prompt_Dialog.setContentView(promptView);
        prompt_Dialog.setCanceledOnTouchOutside(false);

        //各类操作提示对话框相关功能处理
        View setView = LayoutInflater.from(this).inflate(R.layout.check_version, null);
        setDialog_title_tv = (TextView)setView.findViewById(R.id.set_dialog_title);
        setDialog_promptinfo_tv = (TextView)setView.findViewById(R.id.set_dialog_info);
        setDialog_confirm_bt = (TextView)setView.findViewById(R.id.set_dialog_ok_button);
        setDialog_confirm_bt.setOnClickListener(this);
        setDialog_cancel_bt = (TextView)setView.findViewById(R.id.set_dialog_cancel_button);
        setDialog_cancel_bt.setOnClickListener(this);
        set_Dialog = new Dialog(this, R.style.selfdefine_dailog_style);
        set_Dialog.setContentView(setView);
        set_Dialog.setCanceledOnTouchOutside(false);
    }

    private void getVersion()
    {
        String url="http://www.xilingou.com/mobile/index.php?act=index&op=apk_version";
//        {"code":200,"datas":{"version":"3.0","url":""}}
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {}
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
//                            {"code":200,"" +
////            "date":[{"f_id":"1","f_versioncode":"2",
////            "f_size":"22528",
////            "f_downdress":"http:\/\/121.42.195.167:82\/qdshopinterface\/apk\/YangGuangLingGou.apk",
////            "f_versionname":"1.0","f_apkname":"huibao.apk","f_remark":"\u7248\u672c\u66f4\u65b0"}]}
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
//                                toast(String.valueOf(result));
                            if (result == 200) {
                                JSONArray date=resultObject.optJSONArray("date");
                                for (int i = 0; i < date.length(); i++) {
                                    JSONObject recordObject = date.optJSONObject(i);
                                    String version = recordObject.optString("f_versionname");
                                    versionsNum.setText("V" + version);
                                     String url = recordObject.optString("f_downdress");


                                    if (url == "" || url.equals("")) {
                                        verdionsUpdate0.setText("当前您无新版本需要升级");
                                    } else if (url != "") {
                                        verdionsUpdate0.setText("当前您有新版本需要升级");
                                    }


//                                    sureToRecharge.setOnClickListener(new View.OnClickListener() {
//                                        @Override
//                                        public void onClick(View v) {
//                                            updateApk();
//                                            Log.i("zhangxiaoxidebug", "resultinfo=" + url);
//                                        }
//                                    });
                                }

                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();

                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {

                        toast("请求失败");

                    }
                });
    }

    public void onClick(View view){
        switch (view.getId()){
            case R.id.go_back1:
                finish();
                break;
            case R.id.sure_to_recharge:
//                XIAZAI ANZHUANGBAO
                check_update();
                break;
            case R.id.prompt_dialog_button:
                prompt_Dialog.dismiss();
                break;
            case R.id.set_dialog_ok_button:
                File sd= Environment.getExternalStorageDirectory();
                String path=sd.getPath()+"/xilin";
                myfile =new File(path);
                if(!myfile.exists())
                {
                    myfile.mkdir();
                }
                String myAppPath = path +"/" + ApkInfo.apkName;
                downloadApk(myApkinfo.getDownLoadUrl(), myAppPath);
                set_Dialog.dismiss();
                break;
            case R.id.set_dialog_cancel_button:
                set_Dialog.dismiss();
                break;
            default:
                break;
        }
    }
    private void check_update() {
        myApkinfo = new ApkInfo();
        //获取本机版本信息
        try {
            PackageInfo pkg;
            pkg = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            myApkinfo.setOldVersionCode(pkg.versionCode);
            myApkinfo.setOldVersionName(pkg.versionName);

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        String queryUrl = "http://www.xilingou.com/mobile/index.php?act=index&op=apk_version";

        //获取服务器最新版本信息
        checkHttp(queryUrl);
    }
    private void check_update1() {
        myApkinfo = new ApkInfo();
        //获取本机版本信息
        try {
            PackageInfo pkg;
            pkg = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            myApkinfo.setOldVersionCode(pkg.versionCode);
            myApkinfo.setOldVersionName(pkg.versionName);
//            versionsNum.setText("V" + pkg.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        String queryUrl = "http://www.xilingou.com/mobile/index.php?act=index&op=apk_version";



        //获取服务器最新版本信息
        checkHttp1(queryUrl);
    }
    private void checkHttp1(String getUrl)
    {
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.GET,
                getUrl,
                new RequestCallBack<String>()
                {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        chech_over1(responseInfo.result);
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
//                        prompt_title_tv.setText("版本检测");
                        toast("版本检测失败，请检查您的网络稍后再试，如仍有问题请联系客服处理！");
//                        prompt_button_tv.setText("好的");
//                        prompt_Dialog.show();
                    }
                });
    }

    private void chech_over1(String result)
    {
        Log.i("xiaogalade","11"+url);
        Log.i("xiaogalade",result);
        try
        {
            Log.i("xiaogalade11",result);
            JSONObject object = new JSONObject(result);
            int code = object.optInt("code");

//                                toast(String.valueOf(result));
            if (code == 200) {
                JSONArray date=object.optJSONArray("date");
                for (int i = 0; i < date.length(); i++) {
                    Log.i("xiaogalade", String.valueOf(i));
                    JSONObject recordObject = date.optJSONObject(i);
                    Log.i("xiaogalade", String.valueOf(recordObject));
                    double version = recordObject.optDouble("f_versionname");
//                    Log.i("xiaogaladef_versionname", String.valueOf(version));
//                    versionsNum.setText("V" + version);
                    myApkinfo.setNewVersionName(String.valueOf(version));
                    Log.i("xiaogaladeurl","11" );
                    myApkinfo.setNewVersionCode(recordObject.optDouble("f_versionname"));
                    Log.i("xiaogaladeurl","1122" );
//                myApkinfo.setChangeInfo(object.getString("f_remark"));
                    myApkinfo.setDownLoadUrl(recordObject.optString("f_downdress"));
                    Log.i("xiaogaladeurl","33" );}
            }
        } catch (Exception e) {
            Log.i("xiaogaladecuo", String.valueOf(e));

            toast("版本检测失败，请反馈客服处理！");

            return;
        }

        if(myApkinfo.getOldVersionCode() != myApkinfo.getNewVersionCode())
//        if(myApkinfo.getDownLoadUrl()!=null)
        {

            update_flag=true;
            verdionsUpdate0.setText("当前您有新版本需要升级");
            versionsNum.setText("V" +myApkinfo.getOldVersionName());
//            setDialog_promptinfo_tv.setText("当前版本：V"+ myApkinfo.getOldVersionName()

//                    +"\r\n最新版本：V"+ myApkinfo.getNewVersionName()
//                    +"\r\n更新说明：" + myApkinfo.getChangeInfo()
//            );
//            set_Dialog.show();
        }
        else
        {
            verdionsUpdate0.setText("当前您无新版本需要升级");
            versionsNum.setText("V" +myApkinfo.getOldVersionName());
//            prompt_title_tv.setText("版本检测");
//            prompt_info_tv.setText("当前已是最新版本，无需更新！");
//            prompt_button_tv.setText("好的");
//            prompt_Dialog.show();
        }
    }
    private void checkHttp(String getUrl)
    {
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.GET,
                getUrl,
                new RequestCallBack<String>()
                {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        chech_over(responseInfo.result);
                    }

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        prompt_title_tv.setText("版本检测");
                        prompt_info_tv.setText("版本检测失败，请检查您的网络稍后再试，如仍有问题请联系客服处理！");
                        prompt_button_tv.setText("好的");
                        prompt_Dialog.show();
                    }
                });
    }

    private void chech_over(String result)
    {
        Log.i("xiaogalade","11"+url);
        Log.i("xiaogalade",result);
        try
        {
            Log.i("xiaogalade11",result);
            JSONObject object = new JSONObject(result);
            int code = object.optInt("code");

//                                toast(String.valueOf(result));
            if (code == 200) {
                JSONArray date=object.optJSONArray("date");
                for (int i = 0; i < date.length(); i++) {
                    Log.i("xiaogalade", String.valueOf(i));
                    JSONObject recordObject = date.optJSONObject(i);
                    Log.i("xiaogalade", String.valueOf(recordObject));
                    double version = recordObject.optDouble("f_versionname");
                    Log.i("xiaogaladef_versionname", String.valueOf(version));
//                    versionsNum.setText("V" + version);
                myApkinfo.setNewVersionName(String.valueOf(version));
                    Log.i("xiaogaladeurl","11" );
                myApkinfo.setNewVersionCode(recordObject.optDouble("f_versionname"));
                    Log.i("xiaogaladeurl","1122" );
//                myApkinfo.setChangeInfo(object.getString("f_remark"));
                myApkinfo.setDownLoadUrl(recordObject.optString("f_downdress"));
                    Log.i("xiaogaladeurl","33" );}
            }
        } catch (Exception e) {
            Log.i("xiaogaladecuo", String.valueOf(e));
            prompt_title_tv.setText("版本检测");
            prompt_info_tv.setText("版本检测失败，请反馈客服处理！");
            prompt_button_tv.setText("好的");
            prompt_Dialog.show();
            return;
        }

        if(myApkinfo.getOldVersionCode() != myApkinfo.getNewVersionCode())
//        if(myApkinfo.getDownLoadUrl()!=null)
        {

            update_flag=true;

            setDialog_promptinfo_tv.setText("当前版本：V"+ myApkinfo.getOldVersionName()

                    +"\r\n最新版本：V"+ myApkinfo.getNewVersionName()
//                    +"\r\n更新说明：" + myApkinfo.getChangeInfo()
 );
            set_Dialog.show();
        }
        else
        {

            prompt_title_tv.setText("版本检测");
            prompt_info_tv.setText("当前已是最新版本，无需更新！");
            prompt_button_tv.setText("好的");
            prompt_Dialog.show();
        }
    }

    private class ApkInfo {
        private static final String APP_NAME="XiLinMarket";
        private static final String apkName="XiLinMarket.apk";
        private String downLoadUrl;
        private double newVersionCode;
        private int oldVersionCode;
        private String newVersionName;
        private String oldVersionName;
        private String changeInfo;
        public String getDownLoadUrl() {
            return downLoadUrl;
        }
        public void setDownLoadUrl(String downLoadUrl) {
            this.downLoadUrl = downLoadUrl;
        }
        public double getNewVersionCode() {
            return newVersionCode;
        }
        public void setNewVersionCode(double newVersionCode) {
            this.newVersionCode = newVersionCode;
        }
        public int getOldVersionCode() {
            return oldVersionCode;
        }
        public void setOldVersionCode(int oldVersionCode) {
            this.oldVersionCode = oldVersionCode;
        }
        public String getNewVersionName() {
            return newVersionName;
        }
        public void setNewVersionName(String newVersionName) {
            this.newVersionName = newVersionName;
        }
        public String getOldVersionName() {
            return oldVersionName;
        }
        public void setOldVersionName(String oldVersionName) {
            this.oldVersionName = oldVersionName;
        }
        public String getChangeInfo() {
            return changeInfo;
        }
        public void setChangeInfo(String changeInfo) {
            this.changeInfo = changeInfo;
        }
    }

    private void initDialog() {
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
        dialog.setCancelable(true);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        dialog.setIcon(R.drawable.logoup);// 设置提示的title的图标，默认是没有的
        dialog.setTitle("下载进度");
        dialog.setMax(100);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //调用cancel()方法停止下载
                        handler.cancel();
                    }
                });
        dialog.setMessage("正在下载，请稍后...");
        dialog.show();
    }

    private void downloadApk(String srcUrl,String target)
    {
        HttpUtils http = new HttpUtils();
        handler = http.download(srcUrl,target,
                false, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
                new RequestCallBack<File>() {

                    @Override
                    public void onStart() {
                        initDialog();
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        dialog.setProgress((int) (current*100/total));
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        download_over = true;
                        dialog.setMessage("下载成功！");
                        down();
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        dialog.setMessage("下载失败！失败信息："+msg);
                    }
                });
    }

    private void down() {
        new Handler().post(new Runnable() {
            public void run() {
                dialog.dismiss();
                update();
            }
        });
    }

    /**
     * 安装应用
     */
    public void update(){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(myfile,ApkInfo.apkName)), "application/vnd.android.package-archive");
        startActivity(intent);
    }

}
